package com.imooc.controller;

import com.imooc.VO.ProductInfoVO;
import com.imooc.VO.ProductVO;
import com.imooc.VO.ResultVO;
import com.imooc.dataobject.ProductCategory;
import com.imooc.dataobject.ProductInfo;
import com.imooc.service.ProductCategoryService;
import com.imooc.service.ProductInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Buyer Product Controller
 * @author liuhuan
 * @date 2018/7/5 11:18
 * @description
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductCategoryService productCategoryService;

    /**
     * 必须先实现序列化
     *
     * @cacaheable  @CachePut @CacheEcvit(condition ="",unless="result.getCode() !=0")
     * @return
     */
    @GetMapping("list")
    public ResultVO list(){
        //1.查询所有上架商品
        List<ProductInfo> productInfoList=productInfoService.findUpProduct();
        //2.所有上架商品类目
        List<Integer> categoryTypeList=productInfoList.stream().map(productInfo -> productInfo.getCategoryType()).collect(Collectors.toList());
        //3.拼装数据
        List<ProductCategory> categoryList=productCategoryService.findByCategoryTypeIn(categoryTypeList);
        List<ProductVO> productVOList=new ArrayList<>();
        for (ProductCategory productCategory:categoryList) {
            ProductVO productVO=new ProductVO();
            productVO.setCategoryType(productCategory.getCategoryType());
            productVO.setCategoryName(productCategory.getCategoryName());
            List<ProductInfoVO> productInfoVOList=new ArrayList<>();
            for(ProductInfo productInfo:productInfoList){
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoVO productInfoVO=new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo,productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOs(productInfoVOList);
            productVOList.add(productVO);
        }

        return ResultVO.success(productVOList);
    }

}
